/*===============================
 *Title      :  FolderGridActivity.java
 *Created  :[ 2012-3-23 下午1:26:53 ] by fanlt
 * ==============================
 * Description:   
 * Copyright  :  Copyright (c) 2012
 * Company    :  Flyfot
 * @author  <a href="fanlt@flyfot.cn">fanlt</a>
 *
 */
package org.zxstudio.encrypt;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.zxstudio.encrypt.provider.EncryptProvider;
import org.zxstudio.encrypt.task.EncryptListener;
import org.zxstudio.encrypt.task.TaskController;
import org.zxstudio.encrypt.utils.Constant;
import org.zxstudio.encrypt.utils.RLog;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * @author fan
 * 
 */
public class FolderGridActivity extends BaseActivity implements OnClickListener,
		OnItemClickListener, EncryptListener.CallBack {
	private static final String TAG = "FolderGridActivity";
	private static final boolean DEBUG = true;

	private static final int TOKEN_QUERY = 1000;
	private static final int DIALOG_LIST = 10;

	private Cursor mCursor;
	private Button mEncryptBtn;
	private Button mCancelBtn;
	private GridView mGridView;
	private EncryptFileAdapter mAdapter = null;
	private ContentResolver mCr = null;
	QueryEncryptTask mAsyncTask = null;
	TaskController mTc = null;
	ProgressDialog mProgressDialog = null;
	ProgressDialog mProgressQDialog = null;
	
	private long mCurrentId  = 0l;
	
	EncryptQueryHandler mQueryHandler = null;

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			mAdapter.notifyDataSetChanged();
			if (mProgressDialog != null)
				mProgressDialog.dismiss();
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.encrypt_file_view);
		initRes();
	}

	/**
* 
*/
	private void initRes() {
		mCr = this.getContentResolver();
		mQueryHandler  = new EncryptQueryHandler(mCr);
		mTc = TaskController.getInstance(this);
		mTc.registerEncryptListener(this);
		mEncryptBtn = (Button) findViewById(R.id.decrypt);
		mEncryptBtn.setOnClickListener(this);
		mCancelBtn = (Button) findViewById(R.id.cancel);
		mCancelBtn.setOnClickListener(this);
		mGridView = (GridView) findViewById(R.id.gridview);
		mGridView.setOnItemClickListener(this);
		mCr.registerContentObserver(EncryptProvider.ENCRYPT_URI, true, mContentObserver);
		mAdapter = new EncryptFileAdapter(this, mCursor);
		mAdapter.setFolderType();
		mGridView.setAdapter(mAdapter);
	}

	private ContentObserver mContentObserver = new ContentObserver(new Handler()) {

		@Override
		public void onChange(boolean selfChange) {
			super.onChange(selfChange);
			RLog.v(TAG,"onChanged:" + selfChange);
			startQuery();
		}

	};

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mCr.unregisterContentObserver(mContentObserver);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 1, 0, R.string.select_mode);
		return super.onCreateOptionsMenu(menu);
	}

	
	@Override
	protected void onResume() {
		super.onResume();
		startQuery();
		mProgressQDialog = ProgressDialog.show(
				this,
				"",
			getResources().getString(
						R.string.explorer_sd_file));
		mProgressQDialog.setCancelable(true);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch(id) {
		case DIALOG_LIST:
			return new AlertDialog.Builder(FolderGridActivity.this).setItems(R.array.item_options, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					mTc = TaskController.getInstance(FolderGridActivity.this);
					mTc.registerEncryptListener(FolderGridActivity.this);
					if (which == 0) {
						mTc.browseFile(mCurrentId);
					} else if (which == 1) {
						ArrayList<Long> Ids = new ArrayList<Long>(1);
						Ids.add(mCurrentId);
						mTc.decrypt(Ids);
						mTc.registerEncryptListener(FolderGridActivity.this);
					} else if (which == 2) {
						
					}
				}
			}).create();
			
		}
		return super.onCreateDialog(id);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
		case 1:
			mAdapter.changeMode();
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget
	 * .AdapterView, android.view.View, int, long)
	 */
	@Override
	public void onItemClick(AdapterView<?> arg0, View view, int position,
			long id) {
		if (mAdapter.getMode() == EncryptFileAdapter.SELECT_MODE) {
			mAdapter.updateSelectItem(view, id);
		} else {
			Uri uri = ContentUris.withAppendedId(EncryptProvider.ENCRYPT_URI, id);
			Cursor cursor = mCr.query(uri, EncryptProvider.PROJECTIONS, null, null, null);
			if (cursor != null && cursor.moveToFirst()) {
				String path = cursor.getString(4);
				Intent intent = new Intent(this,EncryptFolderActivity.class);
				intent.putExtra(EncryptFolderActivity.FILE_PATH, path);
				startActivity(intent);
			}
			
		}
	
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.decrypt:
			List<Long> items = mAdapter.getSelectedItems();
			if (items.size() > 0) {
				mTc.decrypt(items);
				mTc.registerEncryptListener(this);
				mProgressDialog = ProgressDialog.show(this, "", getResources()
						.getString(R.string.decrypt_file));
				mProgressDialog.setCancelable(true);
			}
			break;
		case R.id.cancel:
			//mAdapter.selectAllItems();
			finish();
			break;
		}
	}

	EncryptFileAdapter.OnContentChangedListener onContentChangedListener = new EncryptFileAdapter.OnContentChangedListener() {

		@Override
		public void onContentChanged(EncryptFileAdapter adapter) {
			RLog.v(TAG, "onContentChangted:");
			startQuery();
		}
	};

	/**
	 * 
	 */
	private void startQuery() {
		mQueryHandler.cancelOperation(TOKEN_QUERY);
		mQueryHandler.startQuery(TOKEN_QUERY, null,
				EncryptProvider.ENCRYPT_URI, EncryptProvider.PROJECTIONS,
				"file_type = " + Constant.TYPE_FOLDER, null, null);
	}

	/**
	 * 
	 * @author fan
	 * 
	 */
	private class EncryptQueryHandler extends AsyncQueryHandler {

		/**
		 * @param cr
		 */
		public EncryptQueryHandler(ContentResolver cr) {
			super(cr);
		}

		@Override
		protected void onDeleteComplete(int token, Object cookie, int result) {
			// TODO Auto-generated method stub
			super.onDeleteComplete(token, cookie, result);
		}

		@Override
		protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
			switch (token) {
			case TOKEN_QUERY:
				RLog.v(TAG, "onQueryComplete:" + cursor.getCount());
				mProgressQDialog.dismiss();
				mAdapter.changeCursor(cursor);
				mAdapter.notifyDataSetChanged();
				break;
			}
		}

		@Override
		protected void onUpdateComplete(int token, Object cookie, int result) {
			super.onUpdateComplete(token, cookie, result);
		}

	}

	private class QueryEncryptTask extends AsyncTask<Integer, Integer, Void> {

		private ProgressDialog dialog;

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			dialog.dismiss();
			mAdapter.changeCursor(mCursor);
			mAdapter.notifyDataSetChanged();
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = ProgressDialog.show(
					FolderGridActivity.this,
					"",
					FolderGridActivity.this.getResources().getString(
							R.string.explorer_sd_file));
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#doInBackground(Params[])
		 */
		@Override
		protected Void doInBackground(Integer... params) {
			mCursor = mCr.query(EncryptProvider.ENCRYPT_URI,
					EncryptProvider.PROJECTIONS, "file_type = "
							+ Constant.TYPE_FOLDER, null, null);
			return null;
		}
	}

	/* (non-Javadoc)
	 * @see org.zxstudio.encrypt.task.EncryptListener.CallBack#browseFile(java.lang.String, java.lang.String)
	 */
	@Override
	public void browseFile(String name, File file) {
		
	}

	/* (non-Javadoc)
	 * @see org.zxstudio.encrypt.task.EncryptListener.CallBack#onError(int)
	 */
	@Override
	public void onError(int code, long id) {
		// TODO Auto-generated method stub
		
	}

	/* (non-Javadoc)
	 * @see org.zxstudio.encrypt.task.EncryptListener.CallBack#onFinish()
	 */
	@Override
	public void onFinish() {
		mHandler.sendEmptyMessageDelayed(0, 300);
	}

	/* (non-Javadoc)
	 * @see org.zxstudio.encrypt.task.EncryptListener.CallBack#onResult(java.io.File, boolean)
	 */
	@Override
	public void onResult(File file, boolean result) {
		
	}

    /* (non-Javadoc)
     * @see org.zxstudio.encrypt.task.EncryptListener.CallBack#onError(int, java.io.File)
     */
    @Override
    public void onError(int code, File file) {
        // TODO Auto-generated method stub
        
    }

    /* (non-Javadoc)
     * @see org.zxstudio.encrypt.task.EncryptListener.CallBack#onShowDialog(int)
     */
    @Override
    public void onShowDialog(int type) {
        // TODO Auto-generated method stub
        
    }

    /* (non-Javadoc)
     * @see org.zxstudio.encrypt.task.EncryptListener.CallBack#onDismissDialog(int)
     */
    @Override
    public void onDismissDialog(int type) {
        // TODO Auto-generated method stub
        
    }
}
